package jsyf.oa.service.device;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.attach.AttachDao;
import jsyf.oa.dao.attach.AttachModuleDao;
import jsyf.oa.dao.contract.ContractMainDao;
import jsyf.oa.dao.contract.ReplacementDao;
import jsyf.oa.dao.device.*;
import jsyf.oa.dao.system.*;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.attach.AttachModuleEntity;
import jsyf.oa.entity.attach.AttachmentEntity;
import jsyf.oa.entity.contract.ContractMainEntity;
import jsyf.oa.entity.device.*;
import jsyf.oa.entity.system.*;
import jsyf.oa.facade.device.DeviceSampleFacade;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;

/**
 * Created by LT on 2018/4/14.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class DeviceSampleService implements DeviceSampleFacade {
    @Autowired
    private DeviceSampleDao deviceSampleDao;
    @Autowired
    private AttachModuleDao attachModuleDao;
    @Autowired
    private DeviceRepaymentPlanDao deviceRepaymentPlanDao;
    @Autowired
    private AttachDao attachDao;
    @Autowired
    private DevicelogisticsDao devicelogisticsDao;
    @Autowired
    private DeviceOutBoundDao deviceOutBoundDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private AuditDao auditDao;
    @Autowired
    private AuditHistoryDao auditHistoryDao;
    @Autowired
    private ContractMainDao contractMainDao;
    @Autowired
    private RegionAchivementsDao regionAchivementsDao;
    @Autowired
    private BigAchievementsDao bigAchievementsDao;
    @Autowired
    private DeviceDisplaceDao deviceDisplaceDao;
    @Autowired
    private MessageReceiverDao messageReceiverDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private DevicePartsDao devicePartsDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private ReplacementDao replacementDao;

    /*获取样机列表*/
    @Override
    public JSONObject getDeviceSampleList(String jsonData) {

        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        //提货公司
        String companyName = jsonParams.getString("companyName");
        //设备类型
        String deviceTypeName = jsonParams.getString("deviceTypeName");
        //品牌
        String brandName = jsonParams.getString("brandName");
        //型号
        String modelName = jsonParams.getString("modelName");
        //状态
        String state = jsonParams.getString("state");
        //模糊查询值
        String key = jsonParams.getString("key");


        String userId = jsonParams.getString("userId");
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and main=1 and id=?", new Object[]{userId});
        String manageFlag = userList.get(0).getString("manageFlag");
        List<JSONObject> companyList = new ArrayList<JSONObject>();
        if (!StringUtils.isBlank(manageFlag)) {
            if (!manageFlag.equals("1")) {
                companyList = companyDao.getJSONListByCondition(" and id in (SELECT \n" +
                        "v_sys_part_time_for_report.companyId\n" +
                        "FROM v_sys_part_time_for_report\n" +
                        "WHERE userId=?)\n" +
                        "and t_sys_company.del_flag=0 AND (t_sys_company.PARENT_ID='201712161613432EAF27DBCCB7D0E6CA')\n" +
                        "group by t_sys_company.id", new Object[]{userId});
            } else {
                companyList = companyDao.getJSONListByCondition(" and del_flag=0 and PARENT_ID='201712161613432EAF27DBCCB7D0E6CA' group by t_sys_company.id", new Object[]{});
            }
        }
        StringBuilder companyIds = new StringBuilder();
        String companyListIds = "";
        //传参
        StringBuffer condition = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<Object>();
        if (companyList.size() > 0) {
            for (JSONObject object : companyList) {
                companyIds.append("'");
                companyIds.append(object.getString("id"));
                companyIds.append("'");
                companyIds.append(",");
            }
            companyListIds = companyIds.toString().substring(0, companyIds.toString().length() - 1);
            condition.append(" and FK_COMPANY_ID in (" + companyListIds + ")");
        }
        condition.append("AND (\n" +
                "t_dvc_sample.AUDIT_FLAG<>-1\n" +
                "OR(t_dvc_sample.AUDIT_FLAG=-1&&t_dvc_sample.CREATE_USER_ID= '" + userId + "'))\n");
        //分页信息
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (jsonParams.containsKey("pageSize")) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (jsonParams.containsKey("requestPage")) {
            requestPage = jsonParams.getInteger("requestPage");
        }

        if (!StringUtils.isBlank(companyName)) {
            if (!"提货公司".equals(companyName)) {
                condition.append(" AND COMPANY_NAME=?");
                sqlArgs.add(companyName);
            }
        }
        if (!StringUtils.isBlank(deviceTypeName)) {
            if (!"设备类型".equals(deviceTypeName)) {
                condition.append(" AND DEVICE_TYPE_NAME=?");
                sqlArgs.add(deviceTypeName);
            }
        }

        if (!StringUtils.isBlank(brandName)) {
            if (!"品牌".equals(brandName)) {
                condition.append(" AND BRAND_NAME=?");
                sqlArgs.add(brandName);
            }
        }
        if (!StringUtils.isBlank(modelName)) {
            if (!"型号".equals(modelName)) {
                condition.append(" AND MODEL_NAME=?");
                sqlArgs.add(modelName);
            }
        }

        if (!StringUtils.isBlank(state)) {
            if (!"状态".equals(state)) {
                condition.append(" AND STATE=?");
                sqlArgs.add(state);
            }
        }
        if (!StringUtils.isBlank(key)) {
            condition.append("  AND (COMPANY_NAME LIKE" + " '%" + key + "%'" + "\n");
            condition.append("OR(DEVICE_TYPE_NAME LIKE" + " '%" + key + "%'" + ")" + "\n");
            condition.append("OR(t_dvc_sample.BRAND_NAME LIKE" + " '%" + key + "%'" + ")" + "\n");
            condition.append("OR(t_dvc_model.MODEL_NAME LIKE" + " '%" + key + "%'" + ")" + "\n");
            if ("库存".equals(key)) {
                condition.append("OR(STATE LIKE '%库存%' OR STATE like '%寄存%')" + "\n");
            }
            condition.append("OR(STATE LIKE" + " '%" + key + "%'" + ")" + "\n");
            condition.append("OR(SEQUENCE LIKE" + " '%" + key + "%'" + ")" + "\n");
            condition.append("OR(SETTLE LIKE" + " '%" + key + "%'" + "))" + "\n");
        }
        JSONObject countList = deviceSampleDao.getAllCount(condition.toString());
        //若为已退货，则按退货时间排序
        if ("已退货".equals(key)) {
            condition.append("  ) as sample ORDER BY sample.stateTime DESC,sample.paixu ASC,sample.auditFlag,sample.pickUpDate DESC,sample.storeAddress DESC,sample.brandName,sample.tonConfig");
        } else {
            condition.append("  ) as sample  GROUP BY sample.sequence  ORDER BY sample.paixu ASC,sample.auditFlag,sample.pickUpDate DESC,sample.storeAddress DESC,sample.brandName,sample.tonConfig");
        }
        //查询LIST
        List<JSONObject> records = deviceSampleDao.getDeviceSampleList(condition.toString(), sqlArgs.toArray(), Integer.valueOf(requestPage), Integer.valueOf(pageSize), key);
        //查询总数
        //Integer recordCount = deviceSampleDao.getPageCount(condition.toString(), sqlArgs.toArray());
        Integer recordCount = deviceSampleDao.getDeviceSampleList(condition.toString(), sqlArgs.toArray(), Integer.valueOf(requestPage), Integer.valueOf(pageSize), key).size();

        //分装前端需要的格式
        int pageCount = 0;
        if (recordCount < pageSize) {
            pageCount = 1;
        } else {
            double flag = Math.ceil(recordCount / pageSize + 1);
            pageCount = ((int) flag);
        }
        if (recordCount == 0) {
            pageCount = 0;
        }
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", records);
        result.put("num", countList);
        return result;

    }

    /*获取设备类型*/
    @Override
    public JSONObject getDeviceTypeList() {
        // JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject obj = new JSONObject();
        StringBuffer condition = new StringBuffer();
        condition.append(" SELECT");
        condition.append(" t_dvc_device_type.ID as id,");
        condition.append(" t_dvc_device_type.`NAME` as `name`");
        condition.append(" FROM t_dvc_device_type ");
        List<JSONObject> records = deviceSampleDao.queryForJsonList(condition.toString(), new Object[]{});
        obj.put("records", records);
        return obj;
    }

    /*添加还款计划表信息*/
    @Override
    public JSONObject addRepaymentPlan(String JsonArray) {
        List<DeviceRepaymentPlanEntity> entity = (List<DeviceRepaymentPlanEntity>) JSONArray.toCollection(JSONArray.fromObject(JsonArray), DeviceRepaymentPlanEntity.class);
        Integer rows = 0;
        for (int i = 0; i < entity.size(); i++) {
            DeviceRepaymentPlanEntity model = entity.get(i);
            rows = deviceRepaymentPlanDao.add(model);
        }
        JSONObject obj = new JSONObject();
        if (rows > 0) {
            obj.put("records", "保存成功");
        } else {
            obj.put("records", "保存失败");
        }
        return obj;
    }

    @Override
    public JSONObject addDevicePartsRecords(String JsonArray) {
        List<DevicePartsEntity> entity = (List<DevicePartsEntity>) JSONArray.toCollection(JSONArray.fromObject(JsonArray), DevicePartsEntity.class);
        Integer rows = 0;
        for (int i = 0; i < entity.size(); i++) {
            DevicePartsEntity model = entity.get(i);
            rows = devicePartsDao.add(model);
        }
        JSONObject obj = new JSONObject();
        if (rows > 0) {
            obj.put("records", "保存成功");
        } else {
            obj.put("records", "保存失败");
        }
        return obj;
    }

    /*修改样机信息*/
    @Override
    public JSONObject updateSample(String jsonData) {
        DeviceSampleEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), DeviceSampleEntity.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        Integer rows = 0;
        /*获取主表信息*/
        DeviceSampleMainEntity deviceSampleMainEntity = entity.getMain();
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //否则会报错
        DeviceSampleMainEntity sampleMainEntity = (DeviceSampleMainEntity) deviceSampleDao.getIBaseEntityById(deviceSampleMainEntity.getId());
        deviceSampleMainEntity.setCreateTime(sampleMainEntity.getCreateTime());
        String id = deviceSampleMainEntity.getId();

        //查询状态有没有改变需不需要审核
        JSONObject sample = deviceSampleDao.getJSONById(id);

        Boolean index = ("库存".equals(sample.getString("state")) || "寄存".equals(sample.getString("state"))) && ("交付在途".equals(deviceSampleMainEntity.getState()));
        if (index || ("2".equals(sample.getString("auditFlag")) && deviceSampleMainEntity.getAuditFlag() == 0)) {
            //首先获取上级为第一审核人
            JSONObject audit = userDao.getFirstParent(deviceSampleMainEntity.getUpdateUserId());
            //修改审核人信息
            deviceSampleMainEntity.setAuditName(audit.getString("name"));
            deviceSampleMainEntity.setAuditId(audit.getString("id"));
            JSONObject user = userDao.getViewJSONListByCondition(" and main=1 and id=?", new Object[]{audit.getString("id")}).get(0);
            deviceSampleMainEntity.setAuditRoleName(user.getString("roleName"));
            deviceSampleMainEntity.setAuditAdvise("");
            deviceSampleMainEntity.setAuditTime(sampleMainEntity.getAuditTime());//前台处理
            //修改审核状态；
            deviceSampleMainEntity.setAuditFlag(deviceSampleMainEntity.getAuditFlag());
            //修改修改人
            deviceSampleMainEntity.setUpdateUserId(deviceSampleMainEntity.getUpdateUserId());
            deviceSampleMainEntity.setUpdateUserName(deviceSampleMainEntity.getUpdateUserName());
            //保留创建人
            deviceSampleMainEntity.setCreateUserId(sampleMainEntity.getCreateUserId());
            deviceSampleMainEntity.setCreateUserName(sampleMainEntity.getCreateUserName());
            if (deviceSampleMainEntity.getUpdateUserId().equals("201711271733404C9DA1461F2421F828")) {
                if (deviceSampleMainEntity.getAuditFlag() == 0) {
                    deviceSampleMainEntity.setAuditFlag(1);
                }
                deviceSampleMainEntity.setAuditId("201711271733404C9DA1461F2421F828");
                deviceSampleMainEntity.setAuditName("曹国玉");
                deviceSampleMainEntity.setAuditRoleName("后台管理");
                deviceSampleMainEntity.setAuditTime(deviceSampleDao.getCurrentTime());
                deviceSampleMainEntity.setAuditAdvise("");
            }
        } else if ("-1".equals(sample.getString("auditFlag"))) {
            //草稿重新提交
            //首先获取上级为第一审核人
            JSONObject audit = userDao.getFirstParent(deviceSampleMainEntity.getCreateUserId());
            //修改审核人信息
            deviceSampleMainEntity.setAuditName(audit.getString("name"));
            deviceSampleMainEntity.setAuditId(audit.getString("id"));
            JSONObject user = userDao.getViewJSONListByCondition(" and main=1 and id=?", new Object[]{audit.getString("id")}).get(0);
            deviceSampleMainEntity.setAuditRoleName(user.getString("roleName"));
            deviceSampleMainEntity.setAuditAdvise("");
            deviceSampleMainEntity.setAuditTime(sampleMainEntity.getAuditTime());
            //修改审核状态；
            deviceSampleMainEntity.setAuditFlag(deviceSampleMainEntity.getAuditFlag());
            //修改修改人
            deviceSampleMainEntity.setUpdateUserId(deviceSampleMainEntity.getCreateUserId());
            deviceSampleMainEntity.setUpdateUserName(deviceSampleMainEntity.getCreateUserName());
            //保留创建人
            deviceSampleMainEntity.setCreateUserId(sampleMainEntity.getCreateUserId());
            deviceSampleMainEntity.setCreateUserName(sampleMainEntity.getCreateUserName());
            if (deviceSampleMainEntity.getUpdateUserId().equals("201711271733404C9DA1461F2421F828")) {
                if (deviceSampleMainEntity.getAuditFlag() == 0) {
                    deviceSampleMainEntity.setAuditFlag(1);
                }
                deviceSampleMainEntity.setAuditId("201711271733404C9DA1461F2421F828");
                deviceSampleMainEntity.setAuditName("曹国玉");
                deviceSampleMainEntity.setAuditRoleName("后台管理");
                deviceSampleMainEntity.setAuditTime(deviceSampleDao.getCurrentTime());
                deviceSampleMainEntity.setAuditAdvise("");
            }
        } else {
            deviceSampleMainEntity.setAuditFlag(Integer.parseInt(sample.getString("auditFlag")));
            //保留创建人
            deviceSampleMainEntity.setAuditTime(sampleMainEntity.getAuditTime());
            deviceSampleMainEntity.setCreateUserId(sampleMainEntity.getCreateUserId());
            deviceSampleMainEntity.setCreateUserName(sampleMainEntity.getCreateUserName());
            deviceSampleMainEntity.setUpdateUserId(deviceSampleMainEntity.getUpdateUserId());
            deviceSampleMainEntity.setUpdateUserName(deviceSampleMainEntity.getUpdateUserName());
        }
        /*保存主表信息*/
        //移库时更改库存地
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if ("移库在途".equals(sampleMainEntity.getState()) && "库存".equals(deviceSampleMainEntity.getState())) {
            DeviceOutBoundMainEntity deviceOutBoundMainEntity = (DeviceOutBoundMainEntity) deviceOutBoundDao.getIBaseEntityByCondition(" AND SAMPLE_ID=? AND TYPE=1 order by CREATE_TIME DESC", new Object[]{id}).get(0);
            deviceSampleMainEntity.setStoreAddress(deviceOutBoundMainEntity.getDelivery_address());
        }
        if (sampleMainEntity.getActualDeliveryDate() != deviceSampleMainEntity.getActualDeliveryDate() && deviceOutBoundDao.getIBaseEntityByCondition(" AND SAMPLE_ID=? AND TYPE=0 order by CREATE_TIME DESC", new Object[]{id}).size() > 0) {
            DeviceOutBoundMainEntity deviceOutBoundMainEntity = (DeviceOutBoundMainEntity) deviceOutBoundDao.getIBaseEntityByCondition(" AND SAMPLE_ID=? AND TYPE=0 order by CREATE_TIME DESC", new Object[]{id}).get(0);
            //实时更新实际交车日期
            if (!StringUtils.isBlank(deviceSampleMainEntity.getActualDeliveryDate())) {
                ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(deviceOutBoundMainEntity.getContractId());
                contractMainEntity.setDeliveryDate(deviceSampleMainEntity.getActualDeliveryDate());
                contractMainDao.update(contractMainEntity);
            }
        }
        if ("交付在途".equals(sampleMainEntity.getState()) && "已交".equals(deviceSampleMainEntity.getState())) {
            if (!"直发客户交机".equals(deviceSampleMainEntity.getStoreAddress())) {
                DeviceOutBoundMainEntity deviceOutBoundMainEntity = (DeviceOutBoundMainEntity) deviceOutBoundDao.getIBaseEntityByCondition(" AND SAMPLE_ID=? AND TYPE=0 order by CREATE_TIME DESC", new Object[]{id}).get(0);
                //更改合同
                ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(deviceOutBoundMainEntity.getContractId());
                contractMainEntity.setSerialNo(deviceSampleMainEntity.getSequence());
                contractMainEntity.setHaveDelivery(1);
                contractMainEntity.setDeliveryDate(deviceSampleMainEntity.getActualDeliveryDate());
                contractMainEntity.setDeliveryAddress(deviceOutBoundMainEntity.getDelivery_address());
                contractMainDao.update(contractMainEntity);
                //将新机序列号插入旧机表
                List<JSONObject> displaceIdList = deviceSampleDao.getDispaceId(contractMainEntity.getId());
                if (displaceIdList != null && displaceIdList.size() > 0) {
                    for (JSONObject displaceJson : displaceIdList) {
                        DeviceDisplaceEntity displaceEntity = (DeviceDisplaceEntity) deviceDisplaceDao.getIBaseEntityById(displaceJson.getString("displaceId"));
                        displaceEntity.setReplacementDeviceSequence(deviceSampleMainEntity.getSequence());
                        displaceEntity.setWhetherToClose("1"); //合同成交，将WHETHER_TO_CLOSE设为‘1’
                        deviceDisplaceDao.update(displaceEntity);
                    }
                }
                String regionManagerId = contractMainEntity.getRegionManagerId();
                String BigRegionId = contractMainEntity.getRegionId();
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
                String month = sdf1.format(new Date());
                int currentMonth = Integer.parseInt(sdf.format(new Date()).split("-")[1]);
                int acturalMonth = Integer.parseInt(deviceSampleMainEntity.getActualDeliveryDate().split("-")[1]);
                String bigMonth = deviceSampleMainEntity.getActualDeliveryDate().substring(0, 7);
                //给区域目标完成表插入数据
                if (regionAchivementsDao.getIBaseEntityByCondition(" AND USER_ID=? AND AREA_ID=? AND ? IN(BEGIN_MONTH,MIDDLE_MONTH,END_MONTH)", new Object[]{regionManagerId, BigRegionId, acturalMonth}).size() > 0) {
                    RegionAchivementsEntity regionAchivementsEntity = (RegionAchivementsEntity) regionAchivementsDao.getIBaseEntityByCondition(" AND USER_ID=? AND AREA_ID=? AND ? IN(BEGIN_MONTH,MIDDLE_MONTH,END_MONTH) ORDER BY CREATE_TIME DESC ", new Object[]{regionManagerId, BigRegionId, acturalMonth}).get(0);
                    int initFinish = 0;
                    if (regionAchivementsEntity.getSaleFinishNum() != null) {
                        initFinish = regionAchivementsEntity.getSaleFinishNum();
                    }
                    regionAchivementsEntity.setSaleFinishNum(initFinish + 1);
                    regionAchivementsDao.update(regionAchivementsEntity);
                }

                //给大区配置表加
                if (bigAchievementsDao.getIBaseEntityByCondition(" AND BIG_AREA_ID=? AND MONTH=?", new Object[]{BigRegionId, bigMonth}).size() > 0) {
                    List<BigAchievementsEntity> bigAchievementsEntitys = bigAchievementsDao.getEntityListByCondition(" AND BIG_AREA_ID=? AND MONTH=?", new Object[]{BigRegionId, bigMonth});
                    for (BigAchievementsEntity bigAchievementsEntity : bigAchievementsEntitys) {
                        BigDecimal alFinishNum = new BigDecimal(0);
                        if ((bigAchievementsEntity.getSaleFinishNum() != null)) {
                            alFinishNum = bigAchievementsEntity.getSaleFinishNum();
                        }
                        BigDecimal num = new BigDecimal(1.00);
                        bigAchievementsEntity.setSaleFinishNum(num.add(alFinishNum));
                        bigAchievementsDao.update(bigAchievementsEntity);
                    }
                }
            } else {
                List<JSONObject> jsonObjects = deviceOutBoundDao.getJSONListByCondition(" AND SAMPLE_ID=? AND TYPE=0 order by CREATE_TIME DESC", new Object[]{id});
                if (jsonObjects.size() == 0) {
                    DeviceOutBoundMainEntity outBoundMainEntity = new DeviceOutBoundMainEntity();
                    outBoundMainEntity.setContractId(deviceSampleMainEntity.getPicture());//此字段代替直发客户交机 选择的合同id
                    outBoundMainEntity.setPickUpAddress("直发客户交机");
                    outBoundMainEntity.setType(0);
                    outBoundMainEntity.setSpecial_fee(deviceSampleMainEntity.getSpecialFee());
                    outBoundMainEntity.setDeduction_fee(deviceSampleMainEntity.getDeductionFee());
                    outBoundMainEntity.setDelivery_address(deviceSampleMainEntity.getDeliveryAddress());
                    outBoundMainEntity.setSampleId(deviceSampleMainEntity.getId());
                    outBoundMainEntity.setCreateUserId(deviceSampleMainEntity.getUpdateUserId());
                    outBoundMainEntity.setCreateUserName(deviceSampleMainEntity.getUpdateUserName());

                    deviceOutBoundDao.add(outBoundMainEntity);
                    ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(deviceSampleMainEntity.getPicture());
                    contractMainEntity.setSerialNo(deviceSampleMainEntity.getSequence());
                    contractMainEntity.setHaveDelivery(1);
                    contractMainEntity.setDeliveryDate(deviceSampleMainEntity.getActualDeliveryDate());
                    contractMainDao.update(contractMainEntity);
                    //将新机序列号插入旧机表
                    List<JSONObject> displaceIdList = deviceSampleDao.getDispaceId(contractMainEntity.getId());
                    if (displaceIdList != null && displaceIdList.size() > 0) {
                        for (JSONObject displaceJson : displaceIdList) {
                            DeviceDisplaceEntity displaceEntity = (DeviceDisplaceEntity) deviceDisplaceDao.getIBaseEntityById(displaceJson.getString("displaceId"));
                            displaceEntity.setReplacementDeviceSequence(deviceSampleMainEntity.getSequence());
                            displaceEntity.setWhetherToClose("1");
                            deviceDisplaceDao.update(displaceEntity);
                        }
                    }
                    String regionManagerId = contractMainEntity.getRegionManagerId();
                    String BigRegionId = contractMainEntity.getRegionId();
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
                    String month = sdf1.format(new Date());
                    int currentMonth = Integer.parseInt(sdf.format(new Date()).split("-")[1]);
                    int acturalMonth = Integer.parseInt(deviceSampleMainEntity.getActualDeliveryDate().split("-")[1]);
                    String bigMonth = deviceSampleMainEntity.getActualDeliveryDate().substring(0, 7);
                    //给区域目标完成表插入数据
                    if (regionAchivementsDao.getIBaseEntityByCondition(" AND USER_ID=? AND AREA_ID=? AND ? IN(BEGIN_MONTH,MIDDLE_MONTH,END_MONTH)", new Object[]{regionManagerId, BigRegionId, acturalMonth}).size() > 0) {
                        RegionAchivementsEntity regionAchivementsEntity = (RegionAchivementsEntity) regionAchivementsDao.getIBaseEntityByCondition(" AND USER_ID=? AND AREA_ID=? AND ? IN(BEGIN_MONTH,MIDDLE_MONTH,END_MONTH) ORDER BY CREATE_TIME DESC ", new Object[]{regionManagerId, BigRegionId, acturalMonth}).get(0);
                        int initFinish = 0;
                        if (regionAchivementsEntity.getSaleFinishNum() != null) {
                            initFinish = regionAchivementsEntity.getSaleFinishNum();
                        }
                        regionAchivementsEntity.setSaleFinishNum(initFinish + 1);
                        regionAchivementsDao.update(regionAchivementsEntity);
                    }

                    //给大区配置表加
                    if (bigAchievementsDao.getIBaseEntityByCondition(" AND BIG_AREA_ID=? AND MONTH=?", new Object[]{BigRegionId, bigMonth}).size() > 0) {
                        List<BigAchievementsEntity> bigAchievementsEntitys = bigAchievementsDao.getEntityListByCondition(" AND BIG_AREA_ID=? AND MONTH=?", new Object[]{BigRegionId, bigMonth});
                        for (BigAchievementsEntity bigAchievementsEntity : bigAchievementsEntitys) {
                            BigDecimal alFinishNum = new BigDecimal(0);
                            if ((bigAchievementsEntity.getSaleFinishNum() != null)) {
                                alFinishNum = bigAchievementsEntity.getSaleFinishNum();
                            }
                            BigDecimal num = new BigDecimal(1.00);
                            bigAchievementsEntity.setSaleFinishNum(num.add(alFinishNum));
                            bigAchievementsDao.update(bigAchievementsEntity);
                        }
                    }
                }
            }
        }
        rows = deviceSampleDao.update(deviceSampleMainEntity);

        if (!deviceSampleMainEntity.getUpdateUserId().equals("201711271733404C9DA1461F2421F828") && deviceSampleMainEntity.getAuditFlag() == 0) {
//标记以前的审核人、申请人消息为已读
            String title = "";
            String bigTitle = "";
            if ("提车在途".equals(deviceSampleMainEntity.getState())) {
                title = Device_AUDIT_AUDIT;
                bigTitle = Device_AUDIT_AUDIT_MESSAGE;
            } else {
                title = Device_STATE_AUDIT;
                bigTitle = Device_AUDIT_STATE_MESSAGE;
            }
            //企业号:给审核人发送消息
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", deviceSampleMainEntity.getAuditId());
            msgObject.put("content", String.format(title,
                    deviceSampleMainEntity.getAuditName(),
                    deviceSampleMainEntity.getModelName(),
                    deviceSampleMainEntity.getSequence(),
                    deviceSampleMainEntity.getCreateUserName(),
                    DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

            messageReceiverRead(deviceSampleMainEntity.getId(), 0);
            messageReceiverRead(deviceSampleMainEntity.getId(), 2);
//付款成功后给申请人发消息，保存消息到消息表t_sys_message
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setCreateUserId(deviceSampleMainEntity.getCreateUserId());
            messageEntity.setCreateTime(deviceSampleDao.getCurrentTime());
            messageEntity.setContent(String.format(title,
                    deviceSampleMainEntity.getAuditName(),
                    deviceSampleMainEntity.getModelName(),
                    deviceSampleMainEntity.getSequence(),
                    deviceSampleMainEntity.getUpdateUserName(),
                    DateUtils.parse(deviceSampleDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
            messageEntity.setMessageType(0);
            messageEntity.setMainId(deviceSampleMainEntity.getId());
            messageEntity.setDelFlag(0);
            messageEntity.setOpenUrl("/page/device/sample/detail_new.html?pageType=look&&id=" + deviceSampleMainEntity.getId() + "&openType=dialog");
            messageEntity.setOpenTitle(String.format(bigTitle, deviceSampleMainEntity.getUpdateUserName()));
            messageDao.add(messageEntity);

            //保存消息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageEntity.getId());
            messageReceiverEntity.setUserId(deviceSampleMainEntity.getAuditId());
            messageReceiverEntity.setUserType(2);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);

            //发消息
            jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
        }

        String mainId = deviceSampleMainEntity.getId();
        //删除还款计划表
        deviceRepaymentPlanDao.removeByCondition(" AND SAMPLE_ID = ? ", new String[]{mainId});
        devicePartsDao.removeByCondition(" AND SAMPLE_ID = ? ", new String[]{mainId});
        /*获取提货合同附件*/
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{mainId});
        List<AttachmentEntity> attachmentEntityList = entity.getAttaches();
        if (attachmentEntityList != null && attachmentEntityList.size() > 0) {
            for (AttachmentEntity attach : attachmentEntityList) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(5);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        //获取司机证件附件
        List<AttachmentEntity> certificateList = entity.getCertificates();
        if (certificateList != null && certificateList.size() > 0) {
            for (AttachmentEntity attach : certificateList) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(6);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        } /*获取设备照片附件*/
        List<AttachmentEntity> devicePictures = entity.getDevicePictures();
        if (devicePictures != null && devicePictures.size() > 0) {
            for (AttachmentEntity attach : devicePictures) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(7);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }/*获取板车照片附件*/
        List<AttachmentEntity> drayPictures = entity.getDrayPictures();
        if (drayPictures != null && drayPictures.size() > 0) {
            for (AttachmentEntity attach : drayPictures) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(8);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        JSONObject obj = new JSONObject();
        if (rows > 0) {
            obj.put("records", "保存成功");
            obj.put("message", jsonObjectList);
        } else {
            obj.put("records", "保存失败");
        }
        return obj;

    }

    /*导出excel*/
    @Override
    public List<JSONObject> getByCondition(String companyName, String deviceTypeName, String brandName, String modelName, String state, String key) {
        //分页信息
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;

        //传参
        StringBuffer condition = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<Object>();

        if (!StringUtils.isBlank(companyName)) {
            if (!"提货公司".equals(companyName)) {
                condition.append(" AND COMPANY_NAME=?");
                sqlArgs.add(companyName);
            }
        }
        if (!StringUtils.isBlank(deviceTypeName)) {
            if (!"设备类型".equals(deviceTypeName)) {
                condition.append(" AND DEVICE_TYPE_NAME=?");
                sqlArgs.add(deviceTypeName);
            }
        }

        if (!StringUtils.isBlank(brandName)) {
            if (!"品牌".equals(brandName)) {
                condition.append(" AND BRAND_NAME=?");
                sqlArgs.add(brandName);
            }
        }
        if (!StringUtils.isBlank(modelName)) {
            if (!"型号".equals(modelName)) {
                condition.append(" AND MODEL_NAME=?");
                sqlArgs.add(modelName);
            }
        }

        if (!StringUtils.isBlank(state)) {
            if (!"状态".equals(state)) {
                condition.append(" AND STATE=?");
                sqlArgs.add(state);
            }
        }

        if (!StringUtils.isBlank(key)) {
            condition.append("AND ( COMPANY_NAME LIKE" + " '%" + key + "%'" + "\n");
            condition.append("OR(DEVICE_TYPE_NAME LIKE" + " '%" + key + "%'" + ")" + "\n");
            condition.append("OR(BRAND_NAME LIKE" + " '%" + key + "%'" + ")" + "\n");
            condition.append("OR(MODEL_NAME LIKE" + " '%" + key + "%'" + ")" + "\n");
            condition.append("OR(STATE LIKE" + " '%" + key + "%'" + "))" + "\n");
        }
        condition.append("ORDER BY PICK_UP_DATE");
        //查询LIST
        List<JSONObject> records = deviceSampleDao.getJSONListByPage(condition.toString(), sqlArgs.toArray(), Integer.valueOf(requestPage), Integer.valueOf(pageSize));
        return records;
    }

    /*修改还款列表*/
    @Override
    public JSONObject updateRepaymentPlan(String JsonArray) {
        List<DeviceRepaymentPlanEntity> entity = (List<DeviceRepaymentPlanEntity>) JSONArray.toCollection(JSONArray.fromObject(JsonArray), DeviceRepaymentPlanEntity.class);
        Integer rows = 0;
        for (int i = 0; i < entity.size(); i++) {
            DeviceRepaymentPlanEntity model = entity.get(i);
            rows = deviceRepaymentPlanDao.add(model);
        }
        JSONObject obj = new JSONObject();
        if (rows > 0) {
            obj.put("records", "保存成功");
        } else {
            obj.put("records", "保存失败");
        }
        return obj;
    }

    /*添加样机信息入库*/
    @Override
    public JSONObject add(String jsonData) {
        DeviceSampleEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), DeviceSampleEntity.class);
        Integer rows = 0;
        /*获取主表信息*/
        DeviceSampleMainEntity deviceSampleMainEntity = entity.getMain();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        List<JSONObject> jsonObjects = deviceSampleDao.getJSONListByCondition("AND SEQUENCE=?", new Object[]{deviceSampleMainEntity.getSequence()});
        if (jsonObjects.size() > 0) {
            JSONObject obj = new JSONObject();
            obj.put("records", "序列号已存在");
            return obj;
        }
        /*保存主表信息*/
        if (!StringUtils.isBlank(deviceSampleMainEntity.getPicture())) {
            deviceSampleMainEntity.setPicture(deviceSampleMainEntity.getPicture().substring(1, deviceSampleMainEntity.getPicture().length()));
        }
        //主表添加审核信息
        //首先获取上级为第一审核人
        JSONObject audit = userDao.getFirstParent(deviceSampleMainEntity.getCreateUserId());
        //设置审核人
        deviceSampleMainEntity.setAuditName(audit.getString("name"));
        deviceSampleMainEntity.setAuditId(audit.getString("id"));
        deviceSampleMainEntity.setAuditAdvise("");
        JSONObject user = userDao.getViewJSONListByCondition(" and main=1 and id=?", new Object[]{audit.getString("id")}).get(0);
        deviceSampleMainEntity.setAuditRoleName(user.getString("roleName"));
        //设置审核状态；
        deviceSampleMainEntity.setAuditFlag(deviceSampleMainEntity.getAuditFlag());
        //设置创建人
        deviceSampleMainEntity.setCreateUserId(deviceSampleMainEntity.getCreateUserId());
        deviceSampleMainEntity.setCreateUserName(deviceSampleMainEntity.getCreateUserName());
        //设置修改人
        deviceSampleMainEntity.setUpdateUserId(deviceSampleMainEntity.getCreateUserId());
        deviceSampleMainEntity.setUpdateUserName(deviceSampleMainEntity.getCreateUserName());
        //曹国玉特殊处理
        if (deviceSampleMainEntity.getCreateUserId().equals("201711271733404C9DA1461F2421F828")) {
            if (deviceSampleMainEntity.getAuditFlag() == 0) {
                deviceSampleMainEntity.setAuditFlag(1);
            }
            deviceSampleMainEntity.setAuditId("201711271733404C9DA1461F2421F828");
            deviceSampleMainEntity.setAuditName("曹国玉");
            deviceSampleMainEntity.setAuditRoleName("后台管理");
            deviceSampleMainEntity.setAuditTime(deviceSampleDao.getCurrentTime());
            deviceSampleMainEntity.setAuditAdvise("");
        }
        rows = deviceSampleDao.add(deviceSampleMainEntity);
        auditDao.removeByCondition("AND MAIN_ID = ? ", new String[]{deviceSampleMainEntity.getId()});

        //审核表添加审核信息
        AuditEntity auditEntity = new AuditEntity();
        auditEntity.setModuleName("newDevice");
        auditEntity.setMainId(deviceSampleMainEntity.getId());
        auditEntity.setAuditFlag(0);
        auditEntity.setAuditAdvise("");
        auditEntity.setAuditorId(audit.getString("id"));
        auditEntity.setAuditorName(audit.getString("name"));
        auditEntity.setAuditSort(0);
        auditEntity.setAuditTime(auditDao.getCurrentTime());
        auditEntity.setRoleName(audit.getString("roleName"));
        auditDao.add(auditEntity);
        if (!deviceSampleMainEntity.getCreateUserId().equals("201711271733404C9DA1461F2421F828") && deviceSampleMainEntity.getAuditFlag() != -1) {

            //企业号:给审核人发送消息
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", auditEntity.getAuditorId());
            msgObject.put("content", String.format(Device_AUDIT_AUDIT,
                    auditEntity.getAuditorName(),
                    deviceSampleMainEntity.getModelName(),
                    deviceSampleMainEntity.getSequence(),
                    deviceSampleMainEntity.getCreateUserName(),
                    DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

            //标记以前的审核人、申请人消息为已读
            messageReceiverRead(deviceSampleMainEntity.getId(), 0);
            messageReceiverRead(deviceSampleMainEntity.getId(), 2);
//付款成功后给申请人发消息，保存消息到消息表t_sys_message
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setCreateUserId(deviceSampleMainEntity.getCreateUserId());
            messageEntity.setCreateTime(deviceSampleDao.getCurrentTime());
            messageEntity.setContent(String.format(Device_AUDIT_AUDIT,
                    auditEntity.getAuditorName(),
                    deviceSampleMainEntity.getModelName(),
                    deviceSampleMainEntity.getSequence(),
                    deviceSampleMainEntity.getCreateUserName(),
                    DateUtils.parse(deviceSampleDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
            messageEntity.setMessageType(0);
            messageEntity.setMainId(deviceSampleMainEntity.getId());
            messageEntity.setDelFlag(0);
            messageEntity.setOpenUrl("/page/device/sample/detail_new.html?pageType=look&&id=" + deviceSampleMainEntity.getId() + "&openType=dialog");
            messageEntity.setOpenTitle(String.format(Device_AUDIT_AUDIT_MESSAGE, deviceSampleMainEntity.getCreateUserName()));
            messageDao.add(messageEntity);

            //保存消息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageEntity.getId());
            messageReceiverEntity.setUserId(auditEntity.getAuditorId());
            messageReceiverEntity.setUserType(2);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);

            //发消息
            jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
        }
        String mainId = deviceSampleMainEntity.getId();
        /*获取提货合同附件*/
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{mainId});
        List<AttachmentEntity> attachmentEntityList = entity.getAttaches();
        if (attachmentEntityList != null && attachmentEntityList.size() > 0) {
            for (AttachmentEntity attach : attachmentEntityList) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(5);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        /*获取司机证件附件*/
        List<AttachmentEntity> certificateList = entity.getCertificates();
        if (certificateList != null && certificateList.size() > 0) {
            for (AttachmentEntity attach : certificateList) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(6);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        /*获取设备照片附件*/
        List<AttachmentEntity> devicePictures = entity.getDevicePictures();
        if (devicePictures != null && devicePictures.size() > 0) {
            for (AttachmentEntity attach : devicePictures) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(7);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        /*获取板车照片附件*/
        List<AttachmentEntity> drayPictures = entity.getDrayPictures();
        if (drayPictures != null && drayPictures.size() > 0) {
            for (AttachmentEntity attach : drayPictures) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(8);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        JSONObject obj = new JSONObject();
        if (rows > 0) {
            obj.put("records", mainId);
            obj.put("message", jsonObjectList);
        } else {
            obj.put("records", "保存失败");
        }
        return obj;

    }

    @Override
    public JSONObject getSampleById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String sampleId = jsonParams.getString("id");
        JSONObject jsonObject = new JSONObject();
        StringBuffer condition = new StringBuffer();
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT * FROM v_com_attach WHERE 1=1" + "\n");
        sql.append("AND moduleId=" + " '" + sampleId + "'" + "AND attach_module=5");
        List<JSONObject> attachs = deviceSampleDao.queryForJsonList(sql.toString(), new Object[]{});
        List<JSONObject> certificates = deviceSampleDao.getcertificateList(sampleId);
        List<JSONObject> devicePictures = deviceSampleDao.getdevicePictures(sampleId);
        List<JSONObject> drayPictures = deviceSampleDao.getdrayPictures(sampleId);

        JSONObject sample = deviceSampleDao.getJSONById(sampleId);
        sample.put("storeDuration", deviceSampleDao.getStorageTime(sampleId) + "天");
        condition.append(" AND SAMPLE_ID=" + " '" + sampleId + "' AND LOG_FLAG=0 ORDER BY EXPIRATION_DATE ASC");
        List<JSONObject> repaymentPlan = deviceRepaymentPlanDao.getJSONListByCondition(condition.toString(), new Object[]{});
        List<JSONObject> deviceParts = devicePartsDao.getJSONListByCondition(" AND SAMPLE_ID=" + " '" + sampleId + "' AND LOG_FLAG=0", new Object[]{});
        /**
         * 物流更改模块
         */
        List<JSONObject> logisticsList = devicelogisticsDao.getJSONListByCondition("AND SAMPLE_ID=? ORDER BY CREATE_TIME DESC", new Object[]{sampleId});
        JSONObject logistics = new JSONObject();
        if (logisticsList.size() > 0) {
            logistics = logisticsList.get(0);
        }
        List<JSONObject> lcertificates = deviceSampleDao.getcertificateList(devicelogisticsDao.getId(sampleId));
        List<JSONObject> ldevicePictures = deviceSampleDao.getdevicePictures(devicelogisticsDao.getId(sampleId));
        List<JSONObject> ldrayPictures = deviceSampleDao.getdrayPictures(devicelogisticsDao.getId(sampleId));
/**
 * 出库模块
 */
        List<JSONObject> outBoundrecordList = deviceOutBoundDao.getJSONListByCondition("AND SAMPLE_ID=? AND TYPE =0 ORDER BY CREATE_TIME DESC", new Object[]{sampleId});
        JSONObject outBoundrecord = new JSONObject();
        if (outBoundrecordList.size() > 0) {
            outBoundrecord = outBoundrecordList.get(0);
            JSONObject contract = contractMainDao.getJSONById(outBoundrecord.getString("contractId"));
            outBoundrecord.put("contract", contract);
        }
        List<JSONObject> outdrayPictures = deviceSampleDao.getdrayPictures(deviceOutBoundDao.getId(sampleId, "0") + "0");
        List<JSONObject> outdevicePictures = deviceSampleDao.getdevicePictures(deviceOutBoundDao.getId(sampleId, "0") + "0");
        List<JSONObject> outcertificates = deviceSampleDao.getcertificateList(deviceOutBoundDao.getId(sampleId, "0") + "0");
/**
 * 移库模块
 */
        List<JSONObject> moverecordList = deviceOutBoundDao.getJSONListByCondition("AND SAMPLE_ID=? AND TYPE =1 ORDER BY CREATE_TIME DESC", new Object[]{sampleId});
        JSONObject moveBoundrecord = new JSONObject();
        if (moverecordList.size() > 0) {
            moveBoundrecord = moverecordList.get(0);
        }
        List<JSONObject> movedrayPictures = deviceSampleDao.getdrayPictures(deviceOutBoundDao.getId(sampleId, "1") + "1");
        List<JSONObject> movedevicePictures = deviceSampleDao.getdevicePictures(deviceOutBoundDao.getId(sampleId, "1") + "1");
        List<JSONObject> movecertificates = deviceSampleDao.getcertificateList(deviceOutBoundDao.getId(sampleId, "1") + "1");

/**
 * 退货模块
 */
        List<JSONObject> exitrecordList = deviceOutBoundDao.getJSONListByCondition("AND SAMPLE_ID=? AND TYPE =2 ORDER BY CREATE_TIME DESC", new Object[]{sampleId});
        JSONObject exitBoundrecord = new JSONObject();
        if (exitrecordList.size() > 0) {
            exitBoundrecord = exitrecordList.get(0);
        }
        List<JSONObject> exitdrayPictures = deviceSampleDao.getdrayPictures(deviceOutBoundDao.getId(sampleId, "2") + "2");
        List<JSONObject> exitdevicePictures = deviceSampleDao.getdevicePictures(deviceOutBoundDao.getId(sampleId, "2") + "2");
        List<JSONObject> exitcertificates = deviceSampleDao.getcertificateList(deviceOutBoundDao.getId(sampleId, "2") + "2");
        /*查询历史审核记录*/
        List<JSONObject> auditHistory = auditHistoryDao.getJSONListByCondition("AND MAIN_ID= '" + sampleId + "'\n", new Object[]{});
        jsonObject.put("auditHistory", auditHistory);
        jsonObject.put("sampleParmsList", sample);
        jsonObject.put("repaymentPlanList", repaymentPlan);
        jsonObject.put("deviceParts", deviceParts);
        jsonObject.put("attaches", attachs);
        jsonObject.put("certificates", certificates);
        jsonObject.put("devicePictures", devicePictures);
        jsonObject.put("drayPictures", drayPictures);
        jsonObject.put("logistics", logistics);
        jsonObject.put("lcertificates", lcertificates);
        jsonObject.put("ldevicePictures", ldevicePictures);
        jsonObject.put("ldrayPictures", ldrayPictures);
        jsonObject.put("outBoundrecord", outBoundrecord);
        jsonObject.put("outcertificates", outcertificates);
        jsonObject.put("outdevicePictures", outdevicePictures);
        jsonObject.put("outdrayPictures", outdrayPictures);
        jsonObject.put("outBoundrecord", outBoundrecord);
        jsonObject.put("outcertificates", outcertificates);
        jsonObject.put("outdevicePictures", outdevicePictures);
        jsonObject.put("outdrayPictures", outdrayPictures);
        jsonObject.put("moveBoundrecord", moveBoundrecord);
        jsonObject.put("movedrayPictures", movedrayPictures);
        jsonObject.put("movedevicePictures", movedevicePictures);
        jsonObject.put("movecertificates", movecertificates);
        jsonObject.put("exitBoundrecord", exitBoundrecord);
        jsonObject.put("exitdrayPictures", exitdrayPictures);
        jsonObject.put("exitdevicePictures", exitdevicePictures);
        jsonObject.put("exitcertificates", exitcertificates);
        return jsonObject;
    }

    /*获取样机及还款列表*/
    @Override
    public JSONObject getSampleAndRepaymentById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String sampleId = jsonParams.getString("id");
        StringBuffer condition = new StringBuffer();
        StringBuffer sql = new StringBuffer();
        JSONObject obj = new JSONObject();
        /*获取样机表信息*/
        JSONObject sample = deviceSampleDao.getJSONById(sampleId);
        sample.put("storeDuration", deviceSampleDao.getStorageTime(sampleId) + "天");
        /*获取样机附件信息*/
        sql.append("SELECT * FROM v_com_attach WHERE 1=1" + "\n");
        sql.append("AND moduleId=" + " '" + sampleId + "'" + "AND attach_module=5");
        List<JSONObject> attachs = deviceSampleDao.queryForJsonList(sql.toString(), new Object[]{});

        List<JSONObject> certificates = deviceSampleDao.getcertificateList(sampleId);

        List<JSONObject> devicePictures = deviceSampleDao.getdevicePictures(sampleId);

        List<JSONObject> drayPictures = deviceSampleDao.getdrayPictures(sampleId);
        /*获取还款计划信息*/
        condition.append(" AND SAMPLE_ID=" + " '" + sampleId + "' AND LOG_FLAG=0 ORDER BY EXPIRATION_DATE ASC");
        List<JSONObject> repaymentPlan = deviceRepaymentPlanDao.getJSONListByCondition(condition.toString(), new Object[]{});
        List<JSONObject> deviceParts = devicePartsDao.getJSONListByCondition(" AND SAMPLE_ID=" + " '" + sampleId + "' AND LOG_FLAG=0", new Object[]{});/**
         * 物流更改模块
         */
        List<JSONObject> logisticsList = devicelogisticsDao.getJSONListByCondition("AND SAMPLE_ID=? ORDER BY CREATE_TIME DESC", new Object[]{sampleId});
        JSONObject logistics = new JSONObject();
        if (logisticsList.size() > 0) {
            logistics = logisticsList.get(0);
        }
        List<JSONObject> lcertificates = deviceSampleDao.getcertificateList(devicelogisticsDao.getId(sampleId));
        List<JSONObject> ldevicePictures = deviceSampleDao.getdevicePictures(devicelogisticsDao.getId(sampleId));
        List<JSONObject> ldrayPictures = deviceSampleDao.getdrayPictures(devicelogisticsDao.getId(sampleId));
/**
 * 出库模块
 */
        List<JSONObject> outBoundrecordList = deviceOutBoundDao.getJSONListByCondition("AND SAMPLE_ID=? AND TYPE =0 ORDER BY CREATE_TIME DESC", new Object[]{sampleId});
        JSONObject outBoundrecord = new JSONObject();
        if (outBoundrecordList.size() > 0) {
            outBoundrecord = outBoundrecordList.get(0);
            JSONObject contract = contractMainDao.getJSONById(outBoundrecord.getString("contractId"));
            outBoundrecord.put("contract", contract);
        }
        List<JSONObject> outdrayPictures = deviceSampleDao.getdrayPictures(deviceOutBoundDao.getId(sampleId, "0") + "0");
        List<JSONObject> outdevicePictures = deviceSampleDao.getdevicePictures(deviceOutBoundDao.getId(sampleId, "0") + "0");
        List<JSONObject> outcertificates = deviceSampleDao.getcertificateList(deviceOutBoundDao.getId(sampleId, "0") + "0");

        /**
         * 移库模块
         */
        List<JSONObject> moverecordList = deviceOutBoundDao.getJSONListByCondition("AND SAMPLE_ID=? AND TYPE =1 ORDER BY CREATE_TIME DESC", new Object[]{sampleId});
        JSONObject moveBoundrecord = new JSONObject();
        if (moverecordList.size() > 0) {
            moveBoundrecord = moverecordList.get(0);
        }
        List<JSONObject> movedrayPictures = deviceSampleDao.getdrayPictures(deviceOutBoundDao.getId(sampleId, "1") + "1");
        List<JSONObject> movedevicePictures = deviceSampleDao.getdevicePictures(deviceOutBoundDao.getId(sampleId, "1") + "1");
        List<JSONObject> movecertificates = deviceSampleDao.getcertificateList(deviceOutBoundDao.getId(sampleId, "1") + "1");

/**
 * 退货模块
 */
        List<JSONObject> exitrecordList = deviceOutBoundDao.getJSONListByCondition("AND SAMPLE_ID=? AND TYPE =2 ORDER BY CREATE_TIME DESC", new Object[]{sampleId});
        JSONObject exitBoundrecord = new JSONObject();
        if (exitrecordList.size() > 0) {
            exitBoundrecord = exitrecordList.get(0);
        }
        List<JSONObject> exitdrayPictures = deviceSampleDao.getdrayPictures(deviceOutBoundDao.getId(sampleId, "2") + "2");
        List<JSONObject> exitdevicePictures = deviceSampleDao.getdevicePictures(deviceOutBoundDao.getId(sampleId, "2") + "2");
        List<JSONObject> exitcertificates = deviceSampleDao.getcertificateList(deviceOutBoundDao.getId(sampleId, "2") + "2");

         /*查询历史审核记录*/
        List<JSONObject> auditHistory = auditHistoryDao.getJSONListByCondition("AND MAIN_ID= '" + sampleId + "'\n", new Object[]{});
        obj.put("auditHistory", auditHistory);
        obj.put("sampleList", sample);
        obj.put("attaches", attachs);
        obj.put("certificates", certificates);
        obj.put("RepaymentPlanList", repaymentPlan);
        obj.put("deviceParts", deviceParts);
        obj.put("devicePictures", devicePictures);
        obj.put("drayPictures", drayPictures);
        obj.put("logistics", logistics);
        obj.put("lcertificates", lcertificates);
        obj.put("ldevicePictures", ldevicePictures);
        obj.put("ldrayPictures", ldrayPictures);
        obj.put("outBoundrecord", outBoundrecord);
        obj.put("outcertificates", outcertificates);
        obj.put("outdevicePictures", outdevicePictures);
        obj.put("outdrayPictures", outdrayPictures);
        obj.put("moveBoundrecord", moveBoundrecord);
        obj.put("movedrayPictures", movedrayPictures);
        obj.put("movedevicePictures", movedevicePictures);
        obj.put("movecertificates", movecertificates);
        obj.put("exitBoundrecord", exitBoundrecord);
        obj.put("exitdrayPictures", exitdrayPictures);
        obj.put("exitdevicePictures", exitdevicePictures);
        obj.put("exitcertificates", exitcertificates);
        return obj;
    }

    @Override
    public JSONObject getById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String deviceSampleid = jsonParams.getString("id");
        return deviceSampleDao.getJSONById(deviceSampleid);
    }

    @Override
    public Boolean update(String jsonData) {
        DeviceSampleMainEntity deviceSampleMainEntity = JSON.toJavaObject(JSON.parseObject(jsonData), DeviceSampleMainEntity.class);
        return deviceSampleDao.update(deviceSampleMainEntity) > 0;
    }

    @Override
    public Boolean delById(String jsonData) {
        return deviceSampleDao.delById(JSON.parseObject(jsonData).getString("id")) > 0;
    }

    @Override
    public Boolean removeById(String jsonData) {
        return deviceSampleDao.removeById(JSON.parseObject(jsonData).getString("id")) > 0;
    }


    @Override
    public List<JSONObject> getBrand(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        System.out.println(userId);
        return deviceSampleDao.getBrand(" AND v_sys_user.id= ?", new Object[]{userId});
    }

    @Override
    public List<JSONObject> getModel(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String brandId = jsonParams.getString("brandId");
        return deviceSampleDao.getModel(" AND t_dvc_brand.ID= ?", new Object[]{brandId});
    }

    @Override
    public List<JSONObject> getRemindReplaymentList() {

        return deviceRepaymentPlanDao.getRemindReplaymentList();
    }

    @Override
    public JSONObject applyAudit(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        String mainId = jsonPalams.getString("id");//获取主表Id
        String auditFlag = jsonPalams.getString("auditFlag");//审核状态
        String userId = jsonPalams.getString("userId");//当前审核人ID
        String advise = jsonPalams.getString("advise");//意见
        UserEntity userEntity = userDao.getById(userId);//获取当前审核人信息
        //添加历史审核记录
        AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
        auditHistoryEntity.setAuditFlag(auditFlag);
        auditHistoryEntity.setMainId(mainId);
        auditHistoryEntity.setAuditAdvise(advise);
        auditHistoryEntity.setAuditorId(userId);
        auditHistoryEntity.setAuditorName(userEntity.getName());
        auditHistoryEntity.setAuditTime(auditHistoryDao.getCurrentTime());
        auditHistoryEntity.setAuditType(8);//新机
        auditHistoryDao.add(auditHistoryEntity);
        //修改主表审核信息----->>>-1未到轮次/初始状态>>>0当前等待审核>>>1通过>>>2驳回
        DeviceSampleMainEntity deviceSampleMainEntity = (DeviceSampleMainEntity) deviceSampleDao.getIBaseEntityById(mainId);
        deviceSampleMainEntity.setAuditFlag(Integer.parseInt(auditFlag));
        deviceSampleMainEntity.setAuditAdvise(advise);
        deviceSampleMainEntity.setAuditTime(auditDao.getCurrentTime());
        deviceSampleDao.update(deviceSampleMainEntity);
        //修改审核表信息----->>>-1未到轮次/初始状态>>>0当前等待审核>>>1通过>>>2驳回
        String title = "";
        if ("提车在途".equals(deviceSampleMainEntity.getState())) {
            title = "入库申请";
        } else {
            title = "交付申请";
        }
        if ("2".equals(auditFlag)) {
            //企业号:给修改人发送消息
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", deviceSampleMainEntity.getUpdateUserId());
            msgObject.put("content", String.format(DEVICE_APPLICATION_REJECT,
                    deviceSampleMainEntity.getUpdateUserName(),
                    title,
                    deviceSampleMainEntity.getModelName(),
                    deviceSampleMainEntity.getSequence(),
                    deviceSampleMainEntity.getAuditAdvise(),
                    userEntity.getName(),
                    DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
            //标记以前的审核人、申请人消息为已读
            messageReceiverRead(mainId, 0);
            messageReceiverRead(mainId, 2);
            //付款成功后给申请人发消息，保存消息到消息表t_sys_message
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setCreateUserId(deviceSampleMainEntity.getAuditId());
            messageEntity.setCreateTime(contractMainDao.getCurrentTime());
            messageEntity.setContent(String.format(DEVICE_APPLICATION_REJECT,
                    deviceSampleMainEntity.getUpdateUserName(),
                    title,
                    deviceSampleMainEntity.getModelName(),
                    deviceSampleMainEntity.getSequence(),
                    deviceSampleMainEntity.getAuditAdvise(),
                    userEntity.getName(),
                    DateUtils.parse(deviceSampleDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
            messageEntity.setMessageType(0);
            messageEntity.setMainId(deviceSampleMainEntity.getId());
            messageEntity.setDelFlag(0);
            messageEntity.setOpenUrl("/page/device/sample/detail_new.html?pageType=look&&id=" + deviceSampleMainEntity.getId() + "&openType=dialog");
            messageEntity.setOpenTitle(String.format(DEVICE_APPLICATION_REJECT_MESSAGE, title, userEntity.getName()));
            messageDao.add(messageEntity);

            //保存消息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageEntity.getId());
            messageReceiverEntity.setUserId(deviceSampleMainEntity.getUpdateUserId());
            messageReceiverEntity.setUserType(2);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);

            //发消息
            jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
        } else {
            //企业号:给修改人发送消息
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", deviceSampleMainEntity.getUpdateUserId());
            msgObject.put("content", String.format(DEVICE_AUDIT_PASS,
                    deviceSampleMainEntity.getUpdateUserName(),
                    title,
                    deviceSampleMainEntity.getModelName(),
                    deviceSampleMainEntity.getSequence(),
                    deviceSampleMainEntity.getAuditName(),
                    DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
            //如果审核通过，当前状态为交付在途或者已交，且交车地点为青海西藏新疆，给隋总发企业微信
            if ("交付在途".equals(deviceSampleMainEntity.getState()) || "已交".equals(deviceSampleMainEntity.getState())) {
                String titleContent = "出库";
                if ("已交".equals(deviceSampleMainEntity.getState())) {
                    titleContent = "交车";
                }
                //获取交车地址
                JSONObject json = deviceSampleDao.getDeliveryAddressBySampleId(mainId);
                if (json != null) {
                    String deliveryAddress = json.getString("deliveryAddress");
                    if (deliveryAddress.indexOf("青海") != -1 || deliveryAddress.indexOf("西藏") != -1 || deliveryAddress.indexOf("新疆") != -1) {
                        msgObject.put("userIds", "20180307111342A6AFC442DC05FD86E2");
                        msgObject.put("content", String.format(Device_Message,
                                "隋华",
                                titleContent,
                                deliveryAddress,
                                deviceSampleMainEntity.getModelName(),
                                deviceSampleMainEntity.getSequence()));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                    }
                }
            }
            //标记以前的审核人、申请人消息为已读
            messageReceiverRead(mainId, 0);
            messageReceiverRead(mainId, 2);
            //付款成功后给申请人发消息，保存消息到消息表t_sys_message
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setCreateUserId(deviceSampleMainEntity.getAuditId());
            messageEntity.setCreateTime(contractMainDao.getCurrentTime());
            messageEntity.setContent(String.format(DEVICE_AUDIT_PASS,
                    deviceSampleMainEntity.getUpdateUserName(),
                    title,
                    deviceSampleMainEntity.getModelName(),
                    deviceSampleMainEntity.getSequence(),
                    deviceSampleMainEntity.getAuditName(),
                    DateUtils.parse(deviceSampleDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
            messageEntity.setMessageType(0);
            messageEntity.setMainId(deviceSampleMainEntity.getId());
            messageEntity.setDelFlag(0);
            messageEntity.setOpenUrl("/page/device/sample/detail_new.html?pageType=look&&id=" + deviceSampleMainEntity.getId() + "&openType=dialog");
            messageEntity.setOpenTitle(String.format(DEVICE_APPLICATION_PASS_MESSAGE, title, userEntity.getName()));
            messageDao.add(messageEntity);

            //保存消息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageEntity.getId());
            messageReceiverEntity.setUserId(deviceSampleMainEntity.getUpdateUserId());
            messageReceiverEntity.setUserType(2);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);
            //发消息
            jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
        }


        auditDao.removeByCondition("AND MAIN_ID = ? ", new String[]{deviceSampleMainEntity.getId()});
        JSONObject user = userDao.getViewJSONListByCondition(" and main=1 and id=?", new Object[]{userId}).get(0);
        //审核表添加审核信息
        AuditEntity auditEntity = new AuditEntity();
        auditEntity.setModuleName("newDevice");
        auditEntity.setMainId(deviceSampleMainEntity.getId());
        auditEntity.setAuditFlag(Integer.parseInt(auditFlag));
        auditEntity.setAuditAdvise(advise);
        auditEntity.setAuditorId(userId);
        auditEntity.setAuditorName(userEntity.getName());
        auditEntity.setAuditSort(0);
        auditEntity.setAuditTime(auditDao.getCurrentTime());
        auditEntity.setRoleName(user.getString("roleName"));
        auditDao.add(auditEntity);

        JSONObject object = new JSONObject();
        object.put("flag", true);
        object.put("message", jsonObjectList);
        return object;
    }

    @Override
    public JSONObject selectStockList(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonPalams.getString("userId");
        String type = jsonPalams.getString("type");
        JSONObject user = userDao.getViewJSONById(userId);
        List<JSONObject> users = userDao.getViewJSONListByCondition(" AND id=? GROUP BY companyId", new Object[]{userId});
        StringBuffer ids = new StringBuffer();
        String companyIds = "";
        for (JSONObject object : users) {
            ids.append("'");
            ids.append(object.getString("companyId"));
            ids.append("'");
            ids.append(",");
        }
        companyIds = ids.toString().substring(0, ids.toString().length() - 1);
        String condition = " AND FK_COMPANY_ID in (" + companyIds + ")";
        if ("1".equals(user.getString("manageFlag")) || "二手机经理".equals(user.getString("roleName"))) {
            condition = "";
        }
        JSONObject records = new JSONObject();
        records.put("newSample", deviceSampleDao.getNewSample(condition, type));
        List<JSONObject> oldSample = deviceDisplaceDao.getOldSample(condition, type);
        List<JSONObject> oldSampleNow = new ArrayList<JSONObject>();
        for (JSONObject object : oldSample) {
            String img = "";
            if (deviceDisplaceDao.getImg(object.getString("id")) != null) {
                img = deviceDisplaceDao.getImg(object.getString("id")).getString("img");
            }
            object.put("img", img);
            oldSampleNow.add(object);
        }
        records.put("oldSample", oldSampleNow);
        records.put("oldHouse", deviceDisplaceDao.getOldHouse(condition, type));
        return records;
    }

    @Override
    public List<JSONObject> getDownByCondition() {
        return deviceSampleDao.getDownByCondition("", new Object[]{});
    }

    //标记消息为已读 /0-审核人 /2-申请人 /1-抄送人(暂无)
    private void messageReceiverRead(String mainId, Integer userType) {
        StringBuffer sb = new StringBuffer();
        List<String> arg = new ArrayList<>();
        if (!org.apache.commons.lang3.StringUtils.isBlank(mainId)) {
            sb.append("AND mainId=?");
            arg.add(mainId);
        }
        if (null != userType) {
            sb.append("AND receiverUserType=?");
            arg.add(userType.toString());
        }
        String receiverIds = "";
        List<JSONObject> jsonObjectList = messageDao.getViewJSONListByCondition(sb.toString(), arg.toArray());
        if (null != jsonObjectList && jsonObjectList.size() > 0) {
            for (int i = 0; i < jsonObjectList.size(); i++) {
                receiverIds += "'" + jsonObjectList.get(i).getString("receiverId") + "',";
            }
        }
        if (receiverIds.length() > 1) {
            receiverIds = receiverIds.substring(0, receiverIds.length() - 1);
        } else {
            receiverIds = null;
        }
        if (!org.apache.commons.lang3.StringUtils.isBlank(receiverIds)) {
            messageReceiverDao.updateReadFlag("T_SYS_MESSAGE_RECEIVER", "AND ID IN (" + receiverIds + ")");
        }
    }

    private JSONObject getMessage(MessageEntity messageEntity, MessageReceiverEntity messageReceiverEntity) {
        String userId = messageEntity.getCreateUserId();
        UserEntity userEntity = userDao.getById(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", messageEntity.getId());
        jsonObject.put("createUserId", userId);
        jsonObject.put("createUserName", userEntity.getName());
        jsonObject.put("createTime", messageEntity.getCreateTime());
        jsonObject.put("content", messageEntity.getContent());
        jsonObject.put("mainId", messageEntity.getMainId());
        jsonObject.put("delFlag", messageEntity.getDelFlag());
        jsonObject.put("openTitle", messageEntity.getOpenTitle());
        jsonObject.put("openUrl", messageEntity.getOpenUrl());
        jsonObject.put("messageType", messageEntity.getMessageType());
        jsonObject.put("receiverId", messageReceiverEntity.getId());
        jsonObject.put("receiverUserId", messageReceiverEntity.getUserId());
        jsonObject.put("receiverUserType", messageReceiverEntity.getUserType());
        jsonObject.put("receiverReadFlag", messageReceiverEntity.getReadFlag());
        return jsonObject;
    }
}
